<script setup>
import { reactive, ref } from 'vue'
import eventBus from '@/utils/eventBus.js'
import { useLoginStore } from '@/store/loginStore'
import { storeToRefs } from 'pinia'
const loginStore = useLoginStore();
const { roleType } = storeToRefs(loginStore)

// 判断用户名和密码是否被保存起来，如果有则直接使用。
const ruleForm = reactive({
    username: localStorage.getItem("username") ?? '',
    password: localStorage.getItem("password") ?? '',
})
// 校验
const rules = reactive({
    username: [
        { required: true, message: '请输入您的账号', trigger: 'blur' }
    ],
    password: [
    { required: true, message: '请输入您的密码', trigger: 'blur' }
    ]
})
const formRef = ref();

eventBus.on('accountLogin',submitForm)

function submitForm(){
    formRef.value?.validate(async(valid) => {
        if (valid) {
            // 发送网络请求
            // 1、获取用户输入的账号和密码
            const username = ruleForm.username;
            const password = ruleForm.password;

            // 2、向服务器发送登录请求
            loginStore.loginRequest({ username, password, roleType: roleType.value });

            // 3、判断是否需要记住密码
            let isRememberPwd = localStorage.getItem('isRememberPwd');
            const isRemPwd = isRememberPwd == 'true' ? true : false;
            if (isRemPwd) {    // 记住，将用户名和密码保存起来
                localStorage.setItem("username", username);
                localStorage.setItem('password', password)
            } else {    // 不记住，将用户名和密码移除
                localStorage.removeItem('username');
                localStorage.removeItem('password');
            }
        }
    })
}
</script>

<template>
  <div class="account_login">
    <el-form
        :model="ruleForm"
        :rules="rules"
        ref="formRef"
    >
        <el-form-item label="账号" prop="username">
            <el-input 
                v-model="ruleForm.username" 
                placeholder="请输入账号" 
            />
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input 
                v-model="ruleForm.password" 
                type="password" 
                show-password
                placeholder="请输入密码"
            />
        </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="less">
</style>